﻿using CefSharp;
using CefSharp.WinForms;
using Common.models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using WebSocket4Net;

namespace dianping_shop_comment_collecter
{
    public partial class Form1 : Form
    {
        public static ChromiumWebBrowser chromeBrowser;
        public static WebSocket websocket;
        public static City city;
        public static Queue<string> queues = new Queue<string>();
        public Form1()
        {
            InitializeComponent();
            InitializeChromium(); 
        }

        void InitializeWebSocket()
        {
            websocket = new WebSocket("ws://localhost:10086/");
            websocket.Opened += Websocket_Opened;
            websocket.Error += Websocket_Error;
            websocket.Closed += Websocket_Closed;
            websocket.MessageReceived += Websocket_MessageReceived;
            websocket.Open();
        }

        private void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Websocket_MessageReceived:" + e.Message);

           var msg = JsonConvert.DeserializeObject<Common.models.Message>(e.Message);

            switch (msg.msgType)
            { 
                case Common.constants.MsgType.BeginFetch:

                    city = JsonConvert.DeserializeObject<Common.models.City>(msg.Data); 
                    if (city.shops.Length > 0)
                    {
                        foreach (var shop in city.shops)
                        {
                            queues.Enqueue(shop);
                        }
                        next();
                    } 

                    break;
                case Common.constants.MsgType.Done:
                    break;
                case Common.constants.MsgType.Exit:
                    break;
                default:
                    break;
            } 
        }


        public static void next()
        {
            if (queues.Count > 0)
            {
                chromeBrowser.Load(queues.Dequeue());
            }
            else
            {
                Process.GetCurrentProcess().Kill();
            }
        }

        private void Websocket_Closed(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Websocket_Closed:");
        }

        private void Websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Websocket_Error:" + e.Exception.Message);
        }

        private void Websocket_Opened(object sender, EventArgs e)
        {
            Debug.WriteLine("Websocket_Opened:");
            Send(new Common.models.Message()
            {
                 msgType = Common.constants.MsgType.Connected,
                 Data = Process.GetCurrentProcess().Id.ToString()
            });
        }


        public static void Send(Common.models.Message message)
        {
            if (websocket.State == WebSocketState.Open)
            {
                websocket.Send(JsonConvert.SerializeObject(message));
            }
        }


        public void InitializeChromium()
        {
            CefSettings settings = new CefSettings();

            ////http://10.8.8.33:5010/get/
            RestSharp.RestRequest req = new RestSharp.RestRequest("/get", RestSharp.Method.GET);
            RestSharp.RestClient client = new RestSharp.RestClient("http://10.8.8.33:5010/");




            settings.CefCommandLineArgs.Add("proxy-server", client.Execute(req).Content);

            // Initialize cef with the provided settings
            Cef.Initialize(settings);
            // Create a browser component

            CheckForIllegalCrossThreadCalls = false;
            chromeBrowser = new ChromiumWebBrowser("http://www.dianping.com/");
             


            chromeBrowser.FrameLoadEnd += ChromeBrowser_FrameLoadEnd;
            chromeBrowser.TitleChanged += ChromeBrowser_TitleChanged;
            chromeBrowser.AddressChanged += ChromeBrowser_AddressChanged;
            chromeBrowser.RequestHandler = new RequestHandler();

            // Add it to the form and fill it to the form window.
            this.splitContainer1.Panel2.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill;
        }

        private void ChromeBrowser_AddressChanged(object sender, AddressChangedEventArgs e)
        {
            textBox1.Text = e.Address;
        }

        private void ChromeBrowser_TitleChanged(object sender, TitleChangedEventArgs e)
        {
            this.Text = e.Title;
        }

        private void ChromeBrowser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(e.Url);
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        { 
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter && !string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                chromeBrowser.Load(textBox1.Text);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            chromeBrowser.ShowDevTools();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InitializeWebSocket();
        }
    }

    internal class RsHd2 : ResourceHandler
    {
        public override bool ProcessRequestAsync(IRequest request, ICallback callback)
        {
            System.Diagnostics.Debug.WriteLine(request.Url);

            
            return base.ProcessRequestAsync(request, callback);
        }
    }
}
